﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using FCNS.Data;

namespace DoubleH.Utility.Configuration
{
    public sealed class ConfigSerializer
    {
        public static UserConfig LoadUserConfig(Int64 userId)
        {
            UserConfig tConfig = null;
            XmlSerializer xmlSerial = new XmlSerializer(typeof(UserConfig));
            FileStream fs = null;
            try
            {
                fs = new FileStream(FCNS.Data.DbDefine.appConfigDir + userId.ToString() + ".xml", FileMode.Open, FileAccess.Read, FileShare.Read);
                tConfig = (UserConfig)xmlSerial.Deserialize(fs);
                fs.Dispose();
            }
            catch (Exception)
            {
                //MessageWindow.Show("配置文件读取异常"); 
                tConfig = new UserConfig();
            }
            return tConfig;
        }

        public static bool SaveConfig(UserConfig userConfigEx, Int64 userId)
        {
            XmlSerializer xmlSerial = new XmlSerializer(typeof(UserConfig));
            Stream fs = new FileStream(FCNS.Data.DbDefine.appConfigDir + userId.ToString() + ".xml", FileMode.Create);
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.Encoding = Encoding.UTF8;
            xws.Indent = true;
            xws.IndentChars = "\t";

            XmlWriter xw = XmlWriter.Create(fs, xws);
            xmlSerial.Serialize(xw, userConfigEx);
            xw.Flush();
            xw.Close();
            if (fs != null)
            {
                fs.Close(); fs = null;
            }
            return true;
        }

        public static object LoadConfig(Type t, string file, bool binaryFormatter = true)
        {
            Debug.Assert(t != null, file);
            InitVar();

            if (!File.Exists(file))
                return t.Assembly.CreateInstance(t.FullName);

            object tConfig = null;
            if (binaryFormatter)
            {
                byte[] by = File.ReadAllBytes(file);
                MemoryStream stream = new MemoryStream(by);
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    tConfig = bf.Deserialize(stream);
                    stream.Dispose();
                    return tConfig;
                }
                catch
                {
                    stream.Dispose();
                    binaryFormatter = false;
                }
            }
            if (!binaryFormatter)
            {
                //MessageWindow.Show("字节序列号配置文件出错" + e1.Message);
                XmlSerializer xmlSerial = new XmlSerializer(t);
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                try
                {
                    tConfig = xmlSerial.Deserialize(fs);
                    fs.Dispose();
                }
                catch
                {
                    //MessageWindow.Show("字节序列号配置文件出错" + e2.Message);
                    fs.Dispose();
                    return t.Assembly.CreateInstance(t.FullName);
                }
            }
            return tConfig;
        }

        public static bool SaveConfig(object config, string file, bool binaryFormatter = true)
        {
            if (binaryFormatter)
            {
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                bf.Serialize(stream, config);
                File.WriteAllBytes(file, stream.ToArray());
                stream.Dispose();
            }
            else
            {
                XmlSerializer xmlSerial = new XmlSerializer(config.GetType());
                Stream fs = new FileStream(file, FileMode.Create);
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.Encoding = Encoding.UTF8;
                xws.Indent = true;
                xws.IndentChars = "\t";

                XmlWriter xw = XmlWriter.Create(fs, xws);
                xmlSerial.Serialize(xw, config);
                xw.Flush();
                xw.Close();
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
            }
            return true;
        }

        private static void InitVar()
        {
            try
            {
                CreateDirectory(DbDefine.extensionDir, DbDefine.printDir, DbDefine.appConfigDir, DbDefine.logDir, DbDefine.langDir);
                CreateDirectory(DbDefine.dataDir, DbDefine.dataDir + "GroupS", DbDefine.dataDir + "ProductS", DbDefine.dataDir + "WeiBaoS", DbDefine.dataDir + "ItDbS");
            }
            catch (Exception error)
            {
                MessageWindow.Show("权限不足." + error.Message);
            }
        }

        private static void CreateDirectory(params string[] directoryName)
        {
            foreach (string str in directoryName)
                if (!Directory.Exists(str))
                    Directory.CreateDirectory(str);
        }
    }
}